import { useRoutes, useNavigate, useLocation } from "react-router-dom"
import { constantRoutes, asyncRoutes } from "@/pages/index"
import { useEffect, useMemo } from "react"
import { useDispatch, useSelector } from "react-redux"
import { getInfo } from "./store/actions";
import { generateRoutes } from "./store/permission";

// 白名单
const whiteList = ["/login"];

function Page() {
  const dispatch = useDispatch();
  const navigator = useNavigate();
  const { token, roles, accessRoutes } = useSelector(state => state.user)
  const { pathname } = useLocation();

  useEffect(() => {
    if (token) {
      dispatch(getInfo())
    } else {
      navigator("/login", { replace: true })
    }
  }, [token])

  useEffect(() => {
    if (roles && roles.length > 0) {
      // 有角色，需要所有的路由表 + 算法，生成当前角色可以访问的路由们
      dispatch(generateRoutes(asyncRoutes, roles))
    }
  }, [roles])

  useEffect(() => {
    if (accessRoutes && accessRoutes.length > 0) {
      navigator("/dashboard", { replace: true })
    }
  }, [accessRoutes])

  useEffect(() => {
    if (!whiteList.includes(pathname) && !token) {
      // 要访问的路由没有在白名单中，并且没有token
      navigator("/login", { replace: true })
    }
    // 已经登录，表示有token了，你又去访问登录页面
    if (token && pathname === "/login") {
      navigator("/", { replace: true })
    }
    if (token && pathname === "/") {
      navigator("/dashboard", { replace: true })
    }
  }, [pathname])

  // 把生成的路由规则们，放到children中
  const routes = useMemo(() => {
    const result = [...constantRoutes];
    result[0].children = accessRoutes;
    return result;
  }, [accessRoutes])



  // 配置规则有两种方式：1）Route组件  2）useRoutes
  const element = useRoutes(constantRoutes);
  return element;
}

export default Page;